import { Asset, AssetManager, AudioClip, Constructor, Prefab, assetManager } from "cc";

/**单例模式的资源管理器 */
export class ResManager {

    /**
     * 加载bundle
     * @param bundleName 包名
     * @param callback 回调
     */
    public loadBundle(bundleName: string, callback?: (bundle: AssetManager.Bundle) => void) {
        assetManager.loadBundle(bundleName, (e, bundle) => {
            callback && callback(bundle);
        });
    }

    /**
     * 加载AssetManager.Bundle接口
     * @param bundleName 
     */
    public loadBundleAsync(bundleName: string): Promise<AssetManager.Bundle> {
        return new Promise<AssetManager.Bundle>(resolve => {
            this.loadBundle(bundleName, resolve);
        })
    }


    /**异步资源加载资源 */
    public loadAssetAsync<T extends Asset>(bUrl: IBundleUrl, type: Constructor<T> | null) {
        return new Promise<T>(resolve => {
            this.loadAsset(bUrl, type, resolve as any);
        })
    }


    /**
     * 加载资源
     * @param bUrl 
     * @param type 
     * @param callBack 
     */
    public loadAsset<T extends Asset>(bUrl: IBundleUrl, type: Constructor<T> | null, callBack: (asset: T | null) => void) {
        assetManager.loadBundle(bUrl.bundleName, (e, bundle) => {
            bundle.load(bUrl.url, type, (err, _asset) => {
                if (err) {
                    console.error(err);
                    return callBack(null);
                }
                callBack(_asset);
            })
        })
    }

    /**获取资源方法 */
    public getAsset<T extends Asset>(bUrl: IBundleUrl, type: Constructor<T> | null): T {
        let assetBundle = assetManager.getBundle(bUrl.bundleName);
        return assetBundle.get(bUrl.url, type);
    }
}